//
//  GMViewController.m
//  GMLive
//
//  Created by gmlive on 2017/3/30.
//  Copyright © 2017年 gmlive. All rights reserved.
//

#import "GMViewController.h"
#import "GMCamera.h"
#import <GPUMatter/GPUMatter.h>
#import "GMGifPlayer.h"
#import "AppTool.h"

#import <GLKit/GLKit.h>

@interface GMViewController ()<GMCameraDelegate,UIGestureRecognizerDelegate,GMGifPlayerDelegate>
{
    
    NSArray *picArr;//图片资源
    
    GMGifPlayer *gifPlayer;//加载并播放GIF
}

@property (weak, nonatomic) IBOutlet UILabel *fpsLabel;
@property (weak, nonatomic) IBOutlet UILabel *cpuLabel;
@property (weak, nonatomic) IBOutlet UIButton *setBtn;
@property (weak, nonatomic) IBOutlet UIButton *pic1Btn;
@property (weak, nonatomic) IBOutlet UIButton *pic2Btn;
@property (weak, nonatomic) IBOutlet UIButton *pic3Btn;
@property (weak, nonatomic) IBOutlet UIButton *gif1Btn;
@property (weak, nonatomic) IBOutlet UIButton *gif2Btn;
@property (nonatomic, strong) GMCamera *camera;
@property (weak, nonatomic) IBOutlet UIButton *changeCameraBtn;
@property (weak, nonatomic) IBOutlet UIView *setBar;
@property (nonatomic, strong) AVSampleBufferDisplayLayer *bufferDisplayer;//buffer显示

@end

@implementation GMViewController

//隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setUpUI];
    
    //初始化摄像头
    [self.camera startCapture];
 
    picArr = @[@"静态1.jpg",@"静态2.jpg",@"静态3.jpg",@"gif1.gif",@"gif2.gif"];
    
    //选中图片静态1
    [self changeBackImg:_pic1Btn];

}

- (void)setUpUI
{
    self.setBar.hidden = YES;
    self.setBar.transform = CGAffineTransformMakeTranslation(0, self.setBar.frame.size.height);
    _pic1Btn.layer.cornerRadius = 5.0;
    _pic2Btn.layer.cornerRadius = 5.0;
    _pic3Btn.layer.cornerRadius = 5.0;
    _gif2Btn.layer.cornerRadius = 5.0;
    _gif1Btn.layer.cornerRadius = 5.0;
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init];
    [gesture addTarget:self action:@selector(touchView:)];
    gesture.delegate = self;
    [self.view addGestureRecognizer:gesture];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.camera startCapture];
    
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.camera stopCapture];
}

//显示摄像头画面
- (AVSampleBufferDisplayLayer *)bufferDisplayer
{
    if (!_bufferDisplayer) {
        _bufferDisplayer = [[AVSampleBufferDisplayLayer alloc] init];
        _bufferDisplayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _bufferDisplayer.frame = self.view.bounds;
        
        [self.view.layer insertSublayer:_bufferDisplayer atIndex:0];
    }
    
    return _bufferDisplayer;
}

//显示设置栏
- (IBAction)showBar:(UIButton *)sender {
    self.setBar.hidden = NO;
    self.setBtn.hidden = YES;
    self.changeCameraBtn.hidden = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.setBar.transform = CGAffineTransformIdentity;
    }];
}

//隐藏设置栏
- (void)touchView:(UITapGestureRecognizer *)gesture
{
    [UIView animateWithDuration:0.5 animations:^{
        self.setBar.transform = CGAffineTransformMakeTranslation(0, self.setBar.frame.size.height);
    } completion:^(BOOL finished) {
        self.setBar.hidden = YES;
        self.setBtn.hidden = NO;
        self.changeCameraBtn.hidden = NO;
    }];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return touch.view == self.view;
}


- (IBAction)changeBackImg:(UIButton *)sender {
    _pic1Btn.selected = sender == _pic1Btn;
    _pic2Btn.selected = sender == _pic2Btn;
    _pic3Btn.selected = sender == _pic3Btn;
    _gif1Btn.selected = sender == _gif1Btn;
    _gif2Btn.selected = sender == _gif2Btn;
    [self updateBtnWithSelectedBtn:sender];
    
    [self updateBackImageWithName:picArr[sender.tag]];
}

- (void)updateBtnWithSelectedBtn:(UIButton *)btn
{
    UIColor *selectedColor = [UIColor colorWithRed:101/255.0 green:199/255.0 blue:198/255.0 alpha:1.0];
    UIColor *normalColor = [UIColor colorWithWhite:1.0 alpha:0.3];
    
    _pic1Btn.backgroundColor = _pic1Btn.selected ? selectedColor:normalColor;
    _pic2Btn.backgroundColor = _pic2Btn.selected ? selectedColor:normalColor;
    _pic3Btn.backgroundColor = _pic3Btn.selected ? selectedColor:normalColor;
    _gif1Btn.backgroundColor = _gif1Btn.selected ? selectedColor:normalColor;
    _gif2Btn.backgroundColor = _gif2Btn.selected ? selectedColor:normalColor;
    
}

//切换背景图
- (void)updateBackImageWithName:(NSString*)name
{
    if ([name hasSuffix:@".jpg"]) {
        if (gifPlayer) {
            [gifPlayer stopGIF];
            gifPlayer = nil;
        }
        [[GPUMatter defaultMatter] updateBackImageWithImage:[UIImage imageNamed:name]];
    }else if ([name hasSuffix:@".gif"])
    {
        //to do
        if (gifPlayer) {
            [gifPlayer stopGIF];
            gifPlayer = nil;
        }
        
        NSString *musicName = [[name componentsSeparatedByString:@"."].firstObject stringByAppendingString:@"-music.mp3"];
        
        gifPlayer = [[GMGifPlayer alloc] initWithGifName:name musicName:musicName];
        gifPlayer.delegate = self;
        [gifPlayer startGIF];
    }
}

//gifPlayer输出图片数据
- (void)gifPlayer:(GMGifPlayer *)player didOutPutImageByte:(GLubyte *)byte WithSize:(CGSize)size
{
    [[GPUMatter defaultMatter] updateBackImageWithBytes:byte size:size];
}

//高斯模糊开关
- (IBAction)gaussianEnableValueChanged:(UISwitch *)sender {
    [GPUMatter defaultMatter].GaussianEnable = sender.isOn;
}

//强度调节
- (IBAction)mattLevelChanged:(UISlider *)sender {
    [GPUMatter defaultMatter].transparency = sender.value;
}

//抠图模式
- (IBAction)MattingModeChanged:(UISegmentedControl *)sender {
    [GPUMatter defaultMatter].mode = (GPUMattingMode)sender.selectedSegmentIndex;
    if ([GPUMatter defaultMatter].mode == GPUMattingModeInvalid) {
        if ([gifPlayer isAnimating]) {
            [gifPlayer pause];
        }
    }else
    {
        if ([gifPlayer isPause]) {
            [gifPlayer startGIF];
        }
    }
}

//切换摄像头
- (IBAction)changeCamera:(UIButton *)sender {
    sender.selected = !sender.selected;
    [_camera changeCameraInputDeviceisFront:sender.selected];
    [_camera startCapture];
}


//摄像头
- (GMCamera *)camera
{
    if (!_camera) {
        _camera = [[GMCamera alloc] initWithCameraPosition:AVCaptureDevicePositionBack captureFormat:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange];
        
        _camera.delegate = self;
        
    }
    
    return _camera;
}

#pragma -GMCameraDelegate
- (void)didOutputVideoSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
    
    /*处理CVPixelBufferRef
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    [[GPUMatter defaultMatter] matPixelBuffer:pixelBuffer];
    */
    
    //获取当前时间
    glFinish();
    CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
    
    //获取帧率及CPU占用率
    [self checkSystemOccupancyWith:currentTime];
    
    [[GPUMatter defaultMatter] matsampleBuffer:sampleBuffer];
    
    //测试耗时
//    [self dealFrameTime:currentTime];
    
    //显示
    CFRetain(sampleBuffer);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.bufferDisplayer.status == AVQueuedSampleBufferRenderingStatusFailed) {
            [self.bufferDisplayer flush];
        }
        
        if ([self.bufferDisplayer isReadyForMoreMediaData]) {
            [self.bufferDisplayer enqueueSampleBuffer:sampleBuffer];
        }
        
        CFRelease(sampleBuffer);
    });

}

//获取帧率及CPU占用率
- (void)checkSystemOccupancyWith:(CFAbsoluteTime)currentTime
{
    int fps = [self dealFPSWith:currentTime];
    int cpu = [AppTool GetCpuUsage];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.cpuLabel.text = [[NSString stringWithFormat: @"CPU : %d",cpu] stringByAppendingString:@"%"];
        self.fpsLabel.text = [NSString stringWithFormat:@"FPS  : %d",fps];
    });
}

//测试帧率
- (int) dealFPSWith:(CFAbsoluteTime)currentTime
{
    static double ftpStartTime = 0;
    if (ftpStartTime == 0) {
        ftpStartTime = currentTime;
    }
    static NSInteger totalCount = 0;
    
    static float fps = 30;
    if (currentTime - ftpStartTime >= 2) {
        
        fps = 1.0 / ((currentTime - ftpStartTime) * 1.0 / totalCount);
        
        fps = floor(fps + 0.5);
        
        ftpStartTime = currentTime;
        totalCount = 0;
    }
    
    totalCount ++;
    
    return (int)fps;
}

//测试耗时
- (void)dealFrameTime:(CFAbsoluteTime)startTime
{
    static int numberOfFramesCaptured = 0;
    static CGFloat totalFrameTimeDuringCapture = 0;
    
    numberOfFramesCaptured++;
    if (numberOfFramesCaptured > 100)
    {
        glFinish();
        CFAbsoluteTime currentFrameTime = (CFAbsoluteTimeGetCurrent() - startTime);
        totalFrameTimeDuringCapture += currentFrameTime;
        
        CGFloat Average = (totalFrameTimeDuringCapture / (CGFloat)(numberOfFramesCaptured - 100)) * 1000.0;
        
        NSLog(@"Average frame time : %f ms", Average);
        NSLog(@"Current frame time : %f ms", 1000.0 * currentFrameTime);
    }
}


@end
